package com.city.parking;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import com.city.parking.util.HttpClientUtil;
import com.city.parking.util.HttpRequest;
import com.city.parking.util.HttpResult;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ReportLocationActivity extends Activity {
	private EditText Name;
	private String mName = "";
	private Button Search;
	private TextView Hint;
	private ListView listView;
	private double mLatitude;
	private double mLongitude;
	private final int SEARCH = 1;
	private final int REPORT = 2;
	private ArrayList<ParkingItem> mList = new ArrayList<ParkingItem>();
    private ParkingListAdapter mAdapter;

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			HttpResult ret = (HttpResult) msg.obj;
			if (msg.arg1 != HttpRequest.NET_SUCCESS || ret == null
					|| ret.status != HttpResult.STATUS_SUCCESS) {
				ParkingApp.showToast("发生错误，请稍后再试");
				return;
			}

			if (msg.what == SEARCH) {
				ArrayList<ParkingItem> list = ParkingItem
						.fromJsonArray(ret.body);
				if (list != null && !list.isEmpty()) {
					mList = list;
					mAdapter.notifyDataSetChanged();
				}
			} else if (msg.what == REPORT) {
				ParkingApp.showToast("更新 "+mName+" 的坐标成功");
				Intent intent = getIntent();
				intent.putExtra("name", mName);
				intent.putExtra("lat", mLatitude);
				intent.putExtra("lng", mLongitude);
				setResult(RESULT_OK, intent);
				finish();
			}
		}
	};

	private void getParkingsByName(String name) {
		String url;
		HttpRequest req;
		if (name == null || name.equals("")) {
//			url = ParkingApp.url_get_all_parks;
//			req = new HttpRequest(url, SEARCH, null, handler);
//			HttpClientUtil.get(req);
			ParkingApp.showToast("请输入关键字");
			return;
		} else {
			url = ParkingApp.url_get_park_by_name;
			JSONObject json = new JSONObject();
			try {
				json.put("name", name);
			} catch (JSONException e1) {
				e1.printStackTrace();
				return;
			}
			req = new HttpRequest(url, SEARCH, json.toString(), handler);
			HttpClientUtil.post(req);
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_report_location);

		Intent intent = this.getIntent(); // 获取已有的intent对象
		Bundle bundle = intent.getExtras(); // 获取intent里面的bundle对象
		mLatitude = bundle.getDouble("lat");
		mLongitude = bundle.getDouble("lng");

		Name = (EditText) findViewById(R.id.name);
		Search = (Button) findViewById(R.id.search);
		Hint = (TextView) findViewById(R.id.hint);		
		Hint.setText("经度："+mLongitude+"°；纬度："+mLatitude +"°");
		listView = (ListView) findViewById(R.id.list);
		mAdapter = new ParkingListAdapter(this);
        listView.setAdapter(mAdapter);
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View v, int pos,
                    long arg3) {
            	final ParkingItem item = (ParkingItem)mAdapter.getItem(pos);
            	mName = item.name;
            	item.latitude = mLatitude;
            	item.longitude = mLongitude;
            	
                new AlertDialog.Builder(ReportLocationActivity.this)
                .setTitle("请确认")
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setMessage("要上报当前位置为"+mName+"吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        // TODO Auto-generated method stub
                		HttpRequest req = new HttpRequest(ParkingApp.url_update_park_field, REPORT, item.toJsonStr(), handler);
                		HttpClientUtil.post(req);
                    }
                }).setNegativeButton("取消", null).show();
            }

        });

		Search.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				String key = Name.getText().toString();
				getParkingsByName(key);
			}
		});
	}

	private class ViewHolder {
		TextView parkingName;
		TextView parkingAddr;
	}

	private class ParkingListAdapter extends BaseAdapter {
		private LayoutInflater inflater = null;

		public ParkingListAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ParkingItem item = mList.get(position);

			ViewHolder holder = null;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = inflater.inflate(R.layout.parking_item, null);
				holder.parkingName = (TextView) convertView
						.findViewById(R.id.parking_name);
				holder.parkingAddr = (TextView) convertView
						.findViewById(R.id.parking_addr);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.parkingAddr.setText(item.addr);
			holder.parkingName.setText(item.name);

			return convertView;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mList.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return mList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}
	}
}